package cn.doitedu.flume;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.flume.Context;
import org.apache.flume.Event;
import org.apache.flume.interceptor.Interceptor;

import java.util.List;

public class EventTimeInterceptor implements Interceptor {

    String timeKey;

    public EventTimeInterceptor() {
    }

    public EventTimeInterceptor(String timeKey) {
        this.timeKey = timeKey;
    }



    // 初始化
    @Override
    public void initialize() {

    }

    // 拦截逻辑
    @Override
    public Event intercept(Event event) {
        // {"username":"a","session_id":"s10","event_id":"search","action_time":1711036401000,"lat":38.089969323508726,"lng":114.35731900345093,"release_channel":"华为应用市场","device_type":"mi8","properties":{"keyword":"usb 移动固态","search_id":"sc01"}}
        byte[] bodyBytes = event.getBody();
        String bodyStr = new String(bodyBytes);

        JSONObject jsonObject = JSON.parseObject(bodyStr);
        Long actionTime = jsonObject.getLong(timeKey);

        if (actionTime != null) {
            // 获取时间戳，并设置到header中
            event.getHeaders().put("timestamp", String.valueOf(actionTime));
        }

        return event;
    }

    // 拦截逻辑：一次输入一批event
    @Override
    public List<Event> intercept(List<Event> events) {
        for (Event event : events) {
            intercept(event);
        }

        return events;
    }


    // 关闭
    @Override
    public void close() {

    }


    public static class MyBuilder implements Interceptor.Builder {

        String timeKey;

        // 创建拦截器实例对象
        @Override
        public Interceptor build() {

            return new EventTimeInterceptor(timeKey);
        }


        // 接收配置参数
        @Override
        public void configure(Context context) {

            this.timeKey = context.getString("time_key");
        }
    }






}
